#include "ec11.h"
#include "usart.h"
#include "main.h"
#include "FreeRTOS.h"
#include "task.h"
#include "delay.h"
void EC11_Init()
{
    GPIO_InitTypeDef GPIO_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;
    EXTI_InitTypeDef EXTI_InitStruct;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_Init(GPIOA, &GPIO_InitStruct);

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource4); // A1
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource5); // A2

    EXTI_InitStruct.EXTI_Line = EXTI_Line4;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling; // down
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStruct);

    EXTI_InitStruct.EXTI_Line = EXTI_Line5;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling; // down
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI4_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x04;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0X00;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI9_5_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x04;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0X00;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

char freq_change_flag = 0;
void EXTI4_IRQHandler(void)
{
    if (A1 == 0 && freq_change_flag == 0)
    {
        delay_us(1000);
        if (B1 == 1) //��ת
        {
            delay_us(1000);
            AD9833.freq += AD9833.freq_d;
        }
        else if (B1 == 0) //��ת
        {
            delay_us(1000);
            AD9833.freq -= AD9833.freq_d;
            if (AD9833.freq <= 0)
                AD9833.freq = 0;
        }
        freq_change_flag = 1;
    }
    EXTI_ClearITPendingBit(EXTI_Line4);
}

void EXTI9_5_IRQHandler(void)
{
    if (A2 == 0)
    {
        delay_us(1000);
        if (B2 == 1) //��ת
        {
            delay_us(1000);
            if (Display.Amplitude < 50)
            {
                Display.Amplitude += 1;
                AD9833.Amplitude = Display.Amplitude * 0.1;
            }
        }
        else if (B2 == 0) //��ת
        {
            delay_us(1000);
            Display.Amplitude -= 1;

            if (Display.Amplitude >= 65535)
                Display.Amplitude = 0;
            AD9833.Amplitude = Display.Amplitude * 0.1;
        }
    }
    EXTI_ClearITPendingBit(EXTI_Line5);
}
